// api/testdetail.js
import { get } from '../utils/request'

/**
 * 根据测评ID获取题目列表（包含选项）
 * @param {Number} assessmentId - 测评ID
 * @returns {Promise}
 */
export const getAssessmentQuestions = async (assessmentId) => {
  try {
    console.log('🎯 API调用: getAssessmentQuestions, assessmentId:', assessmentId)
    
    // 1. 获取题目列表 - 注意：接口返回的是直接数组
    const questionsArray = await get('/app-api/mp/open/question/list', {
      assessmentId: assessmentId,
      pageNo: 1,
      pageSize: 100
    })

    console.log('📋 题目列表接口响应:', questionsArray)
    console.log('📊 题目列表数据:', questionsArray)
    console.log('🔢 题目数量:', questionsArray.length)

    // 修正：接口返回的是直接数组，不是 { list: [], total: number } 结构
    if (!questionsArray || questionsArray.length === 0) {
      console.log('❌ 题目列表为空')
      throw new Error('该测评暂无题目')
    }

    // 2. 为每个题目获取对应的选项
    console.log('🔄 开始获取题目选项...')
    const questionsWithOptions = await Promise.all(
      questionsArray.map(async (question, index) => {
        console.log(`📝 处理第${index + 1}个题目:`, question)
        
        // 获取该题目的选项
        const optionsArray = await get('/app-api/mp/open/option/list', {
          questionId: question.id,
          pageNo: 1,
          pageSize: 50
        })

        console.log(`📝 题目${question.id}的选项:`, optionsArray)

        // 格式化选项数据 - 选项接口也返回直接数组
        const formattedOptions = (optionsArray || []).map((option, optIndex) => ({
          id: option.id,
          label: String.fromCharCode(65 + optIndex), // A, B, C, D...
          text: option.optionText,
          value: option.optionValue || option.id,
          sort: option.sort || 0
        }))

        // 按sort字段排序选项
        formattedOptions.sort((a, b) => a.sort - b.sort)

        const formattedQuestion = {
          id: question.id,
          title: question.questionText,
          type: question.questionType,
          sort: question.sort || 0,
          required: question.required,
          options: formattedOptions
        }
        
        console.log(`✅ 格式化后的题目${index + 1}:`, formattedQuestion)
        return formattedQuestion
      })
    )

    console.log('🎉 最终所有题目数据:', questionsWithOptions)
    return questionsWithOptions

  } catch (error) {
    console.error('❌ 获取测评题目失败:', error)
    throw error
  }
}